package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.RCompanyRole;
import com.emily.test.model.TRole;
import com.emily.test.service.RCompanyRoleService;
import com.emily.test.service.RedisService;
import com.emily.test.service.RoleService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.DateUtil;
import com.emily.test.utils.HeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.mail.Header;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
@RequestMapping(value = "role")
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
/**
 * @author ：zc
 * @date ：Created in 2019/3/8 11:35
 * @description：角色相关接口
 */
@Api(value = "RoleApi", description = "Role接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class RoleController {
    private Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private RoleService roleService;
    @Autowired
    private RCompanyRoleService rCompanyRoleService;
    @Autowired
    private RedisService redisService;

    @ApiOperation(value="获取角色信息列表", notes="获取所有角色信息",httpMethod="GET")
    @PostMapping(value = "/role")
    public ResponseResult selectRole(HttpServletRequest request) {
        List<Map<String,Object>> userRoleList=HeaderUtil.getUserRoleList(request,redisService);
        boolean flag=false;
        //判断该用户是否为超管，如果是，则显示所有角色，否则显示用户公司下的角色
        if(!ConstentUtil.isEmpty(userRoleList)){
            for(Map<String,Object> roleMap : userRoleList){
                String roleName= (String) roleMap.get("roleName");
                String roleCode= (String) roleMap.get("roleCode");
                if("超级管理员".equals(roleName) && "SUPERADMIN".equals(roleCode)){
                    flag=true;
                    break;
                }
            }
        }
        try {
            List<TRole> roleList=new ArrayList<TRole>();
            if(flag){
                //如果是超管，则查询所有角色信息
                roleList= roleService.selectRole();
            }else{
                Integer companyId=HeaderUtil.getCompanyId(request,redisService);
                //获取所有启用的本公司下的角色信息
                List<Map<String,Object>> tRoleList=roleService.selectTRoleInfoListByCompanyId(ConstentUtil.strToList(Integer.toString(companyId)));
                if(!ConstentUtil.isEmpty(tRoleList)){
                    for(Map<String,Object> tRoleMap : tRoleList){
                        TRole role=new TRole();
                        role.setId((Integer) tRoleMap.get("roleId"));
                        role.setSerial((Integer) tRoleMap.get("serial"));
                        role.setUpdateTime((String) tRoleMap.get("rolUpdateTime"));
                        role.setState((Integer) tRoleMap.get("roleState"));
                        role.setrCode((String) tRoleMap.get("rCode"));
                        role.setrName((String) tRoleMap.get("rName"));
                        role.setDescription((String) tRoleMap.get("description"));
                        roleList.add(role);
                    }
                }
            }
            logger.info("该登录用户是否为超管:{}",flag);
            logger.info("获取用户的角色信息{}",roleList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,  roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    @ApiOperation(value="根据公司ID获取角色信息列表", notes="根据公司ID获取角色信息列表")
    @PostMapping(value = "getRolesByCompanyId")
    public ResponseResult getRolesByCompanyId(HttpServletRequest request) {
        //获取登录人的信息
        String token = request.getHeader("token");
        System.out.println("token===="+token);
        Map<String,Object> userMap=  (Map<String,Object>)redisService.get(token);
        Integer companyId= (Integer) userMap.get("companyId");
        try {
            //获取所有启用的本公司下的角色信息
            List<Map<String,Object>> tRoleList=roleService.selectTRoleInfoListByCompanyId(ConstentUtil.strToList(Integer.toString(companyId)));
            List<TRole> roleList =new ArrayList<TRole>();
            if(!ConstentUtil.isEmpty(tRoleList)){
                for(Map<String,Object> tRoleMap : tRoleList){
                    TRole role=new TRole();
                    role.setId((Integer) tRoleMap.get("roleId"));
                    role.setSerial((Integer) tRoleMap.get("serial"));
                    role.setUpdateTime((String) tRoleMap.get("rolUpdateTime"));
                    role.setState((Integer) tRoleMap.get("roleState"));
                    role.setrCode((String) tRoleMap.get("rCode"));
                    role.setrName((String) tRoleMap.get("rName"));
                    role.setDescription((String) tRoleMap.get("description"));
                    roleList.add(role);
                }
            }
            logger.info("根据公司ID获取角色信息列表{}",roleList);
            return ResponseResult.success(roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }



    /**
     * 获取公司内部没有添加资源的角色信息列表
     * @return
     */
    @ApiOperation(value="获取公司内部没有添加资源的角色信息列表", notes="获取没有添加资源的角色信息列表")
    @PostMapping(value = "/selectRoleListNoResourceInCompany")
    public ResponseResult selectRoleListNoResource(HttpServletRequest request) {
        Integer companyId =HeaderUtil.getCompanyId(request,redisService);
        try {
            List<TRole> roleList= roleService.selectRoleListNoResourceInCompany(companyId);
            logger.info("获取没有添加资源的角色信息列表{}",roleList);
            return ResponseResult.success("0", ReturnValueConstants.QUERY_SUCCESS,  roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    @ApiOperation(value="获取没有添加资源的角色信息列表", notes="获取没有添加资源的角色信息列表")
    @PostMapping(value = "/selectRoleListNoResource")
    public ResponseResult selectRoleListNoResource() {
        try {
            List<TRole> roleList= roleService.selectRoleListNoResource();
            logger.info("获取没有添加资源的角色信息列表{}",roleList);
            return ResponseResult.success("0", "查询成功",  roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    @ApiOperation(value="获取没有添加菜单的角色信息列表", notes="获取没有添加菜单的角色信息列表")
    @PostMapping(value = "/selectRoleListNoMenu")
    public ResponseResult selectRoleListNoMenu() {
        try {
            List<TRole> roleList= roleService.selectRoleListNoMenu();
            logger.info("获取没有添加菜单的角色信息列表{}",roleList);
            return ResponseResult.success(roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    @ApiOperation(value="获取角色信息", notes="根据id获取角色信息",httpMethod="GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true)
    })
    @PostMapping(value = "/role/{id}")
    public ResponseResult selectRoleById(@PathVariable("id") Integer id) {
        try {
            TRole tRole = roleService.selectRoleById(id);
            logger.info("获取ID为{}的角色信息", tRole);
            return ResponseResult.success("0", "查询成功", tRole);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    @ApiOperation(value="删除角色信息", notes="根据id删除角色信息",httpMethod="DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true)
    })
    @PostMapping(value = "/deleteRoleById/{id}")
    public ResponseResult deleteRoleById(@PathVariable("id") Integer id){
        try {
            TRole tRole = roleService.selectRoleById(id);
            tRole.setState(2);
            roleService.updateRoleById(tRole);
            logger.info("id为{}的角色已删除",id);
            return ResponseResult.success("0","删除成功",tRole);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除成功");
        }
    }

    /**
     * 根据提供的角色id数组禁用多个角色信息
     * @param jsonObject    其中角色ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="禁用多个角色信息", notes="根据id禁用角色信息",httpMethod="DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "角色ID列表", required = true)
    })
    @PostMapping(value = "disabledRoleById")
    public ResponseResult disabledRoleById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TRole> tRoleList=new ArrayList<TRole>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TRole tRole=new TRole();
                tRole.setId(ConstentUtil.strToInteger(idStr[i]));
                tRole.setState(0);
                tRoleList.add(tRole);
            }
        }
        try {
            roleService.updateRoleByIds(tRoleList);
            logger.info("ids为{}的角色已禁用",ids);
            return ResponseResult.success("0","禁用成功",tRoleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("禁用失败");
        }
    }

    /**
     * 根据提供的角色id数组启用多个角色信息
     * @param jsonObject    其中角色ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value="启用多个角色信息", notes="根据id启用角色信息",httpMethod="DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "角色ID列表", required = true)
    })
    @PostMapping(value = "enabledRoleById")
    public ResponseResult enabledRoleById(@RequestBody JSONObject jsonObject){
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TRole> tRoleList=new ArrayList<TRole>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                TRole tRole=new TRole();
                tRole.setId(ConstentUtil.strToInteger(idStr[i]));
                tRole.setState(1);
                tRole.setUpdateTime(DateUtil.getNowStr());
                tRoleList.add(tRole);
            }
        }
        try {
            roleService.updateRoleByIds(tRoleList);
            logger.info("ids为{}的角色已启用",ids);
            return ResponseResult.success("0","启用成功",tRoleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("启用成功");
        }
    }

    /**
     * 根据提供的角色id数组删除多个角色信息（假删除）
     * @param jsonObject    其中角色ids的格式为:{1,2,3,4}
     * @return
     */
    @ApiOperation(value="删除多个角色信息", notes="根据id删除角色信息",httpMethod="DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "角色ID列表", required = true)
    })
    @PostMapping(value = "deleteRoleById")
    public ResponseResult deleteRoleById(@RequestBody JSONObject jsonObject){
//        jsonObject.get
        String ids=jsonObject.getString("ids").replaceAll("\\[","").replaceAll("]","");
        String[] idStr=ids.split(",");
        List<TRole> tRoleList=new ArrayList<TRole>();
        if(idStr.length !=0){
            for( int i=0;i<idStr.length;i++){
                 TRole tRole=new TRole();
                 tRole.setId(ConstentUtil.strToInteger(idStr[i]));
                 tRole.setState(2);
                 tRoleList.add(tRole);
            }
        }
        try {
            roleService.updateRoleByIds(tRoleList);
            logger.info("ids为{}的角色已删除",ids);
            return ResponseResult.success("0","删除成功",tRoleList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除成功");
        }
    }

    @ApiOperation(value="添加角色信息", notes="添加角色信息",httpMethod="POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "角色名", required = true),
            @ApiImplicitParam(name = "code", value = "角色code", required = true),
            @ApiImplicitParam(name = "state", value = "角色状态", required = true),
            @ApiImplicitParam(name = "serial", value = "角色显示顺序", required = true),
            @ApiImplicitParam(name = "description", value = "备注", required = true)
    })
    @PostMapping(value = "/insertRole")
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public ResponseResult insertRole(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        logger.info("添加的数据为{}",jsonObject.toJSONString());
        try {
            int id = HeaderUtil.getCompanyId(request,redisService);
            String companyCode=HeaderUtil.getCompanyCode(request,redisService);
            TRole role= (TRole) ConstentUtil.json2Object(jsonObject,TRole.class);
            role.setUpdateTime(DateUtil.getNowStr());
            role.setrCode(companyCode+role.getrCode());
            roleService.insertRole(role);
            RCompanyRole rCompanyRole = new RCompanyRole();
            rCompanyRole.setCompanyId(id);
            rCompanyRole.setRoleId(role.getId());
            rCompanyRoleService.insert(rCompanyRole);
            logger.info("新添加的角色id为{}", role.getId());
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS, role);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }
    @ApiOperation(value="修改角色信息", notes="修改角色信息",httpMethod="PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色id", required = true),
            @ApiImplicitParam(name = "name", value = "角色名", required = true),
            @ApiImplicitParam(name = "code", value = "角色code", required = true),
            @ApiImplicitParam(name = "state", value = "角色状态", required = true),
            @ApiImplicitParam(name = "serial", value = "角色显示顺序", required = true),
            @ApiImplicitParam(name = "description", value = "备注", required = true)
    })
    @PostMapping(value = "/updateRoleById")
    public ResponseResult updateRoleById(@RequestBody JSONObject jsonObject) {
//        String companyCode=HeaderUtil.getCompanyCode(request,redisService);
        try {
            TRole role= (TRole) ConstentUtil.json2Object(jsonObject,TRole.class);
//            role.setrCode(companyCode+role.getrCode());
            role.setUpdateTime(DateUtil.getNowStr());
            System.out.println(role);
            roleService.updateRoleById(role);
            logger.info("修改的角色id为{}", role.getId());
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS, role);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 根据公司ID查询所有角色信息列表,显示格式为company信息
     * @param jsonObject 公司ID集合，其中参数key为companyIds，值形式为:"1,2,3,4"
     * @return
     */
    @ApiOperation(value="根据公司ID查询所有角色信息列表", notes="TRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyIds", value = "公司ID集合", required = true)
    })
    @PostMapping(value = "selectTRoleInfoByRoleIds")
    public ResponseResult selectTRoleInfoByRoleIds(@RequestBody JSONObject jsonObject){
        String companyIds=jsonObject.getString("companyIds");
        try {
            List<Map<String,Object>> tRoleList= roleService.selectTRoleInfoListByCompanyId(ConstentUtil.strToList(companyIds));
            String[] strs = companyIds.split(",");
            List all_list = new ArrayList();
            for (int j = 0; j < strs.length; j++) {
                HashMap<String, Object> hm = new HashMap<>();
                List list1 = new ArrayList();
                for (int i = 0; i < tRoleList.size(); i++) {
                    if(strs[j].equals(tRoleList.get(i).get("companyId").toString())) {
                        hm.put("companyId", strs[j]);
                        hm.put("cName", tRoleList.get(i).get("cName").toString());
                        list1.add(tRoleList.get(i));
                        hm.put("data",list1);
                    }
                }
                if(hm.size()!=0){
                    all_list.add(hm);
                }
            }
            logger.info("查询t_role成功，list={}",all_list);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,all_list);
        } catch (Exception e) {
            logger.error("查询t__role异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }
    /**
     * 根据查询条件查询符合条件的角色集合,其中删除的不显示
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据查询条件查询符合条件的角色集合", notes="TRole")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "companyIds", value = "公司ID集合", required = true)
    })
    @PostMapping(value="selectRoleListByCondition")
    public ResponseResult selectRoleListByCondition(@RequestBody JSONObject jsonObject){
        Integer id=jsonObject.getInteger("id");
        String rName=jsonObject.getString("rName");
        String rCode=jsonObject.getString("rCode");
        Integer state=jsonObject.getInteger("state");
        Integer serial=jsonObject.getInteger("serial");
        String description=jsonObject.getString("description");
        String updateTime=jsonObject.getString("updateTime");
        TRole tRole=new TRole();
        tRole.setId(id);
        tRole.setrName(rName);
        tRole.setrCode(rCode);
        tRole.setState(state);
        tRole.setSerial(serial);
        tRole.setDescription(description);
        tRole.setUpdateTime(updateTime);
        try {
            List<TRole> tRoleList=roleService.selectRoleByCondition(tRole);
            return ResponseResult.success(tRoleList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据查询条件查询符合条件的角色集合异常:",e);
            return ResponseResult.fail("查询失败");
        }
    }

}
